package md.mru.frontend.validators;

import md.mru.frontend.controllers.AuthenticationBean;
import org.springframework.security.crypto.bcrypt.BCrypt;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * @author sergiu.marin
 * @since 07/06/2014.
 */
@ManagedBean
@RequestScoped
public class UserPasswordValidator implements Validator {

    @ManagedProperty(value = "#{authenticationBean}")
    private AuthenticationBean authenticationBean;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        //String oldPassword = BCrypt.hashpw((String) value, BCrypt.gensalt());
        if (!BCrypt.checkpw((String) value, authenticationBean.getLoginUser().getUser().getPassword())) {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Parola veche incorecta.", null));
        }
    }

    public void setAuthenticationBean(AuthenticationBean authenticationBean) {
        this.authenticationBean = authenticationBean;
    }
}
